/**
 * 根据config.json自动生成相应环境的配置文件
 * @author zhangzc
 */

var fs = require('fs');

var exitIf = function(condition){
    if(condition){
        console.log('Auto generate deploy configuration tools.');
        console.log('Usage: node deploy.js [prod|dev]');
        process.exit(0);
    }
    
}

exitIf(process.argv.length < 3);

var config = JSON.parse(fs.readFileSync('deploy.json', {encoding: 'utf-8'}));
var configDir = config.config;
var deployEnv = config[process.argv[2]];
exitIf(!deployEnv);

var files = fs.readdirSync(configDir);
    
files.forEach(file=>{
    var filePath = configDir + '/' + file;
    // console.log(filePath);
    if(file.endsWith('.example')){ //找到vue组件
        var fileName = filePath.substr(0, filePath.length - '.example'.length);
        console.log('file: '+ fileName);
        var fileContent = fs.readFileSync(filePath, {encoding: 'utf-8'});
        // console.log('fileContent: '+ fileContent);
        fileContent = '/*Auto generated by deploy.js*/\n\n' + fileContent;
        for(var i in deployEnv){
            fileContent = fileContent.replace('#'+i+'#', deployEnv[i]);
        }
        fs.writeFileSync(fileName,fileContent);
    }
})

